# -*- coding: utf-8 -*-
__author__ = 'Paul'
import random
from zope import schema
from zope.formlib import form
from plone.directives import form as formu
from zope.interface import implements
from zope.component import getMultiAdapter
from plone.app.portlets.portlets import base
from plone.memoize.instance import memoize
from plone.portlets.interfaces import IPortletDataProvider
from DateTime import DateTime
from Products.Five.browser.pagetemplatefile import\
    ViewPageTemplateFile
from Products.CMFCore.utils import getToolByName
from Products.bpContents import _
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
from Acquisition import aq_inner
from plone.memoize.compress import xhtml_compress
from Products.bpContents.articulo import IArticulo
from Products.bpContents.galeria import IGaleria
from Products.bpContents.evento import IEvento
from zope.schema.interfaces import IVocabularyFactory

from zope.site.hooks import getSite
import unicodedata
from intereses_portlets import CanalesVocabularyFactory
from plone.app.vocabularies.catalog import SearchableTextSourceBinder
CanalesVocabularyFactory
from Products.ATContentTypes.interface import IATFolder, IATImage,\
    IATBTreeFolder, IATDocument
from collective.portlet.foldercontents.widget import FixedErrorMessageChoiceInputWidget
from Products.bpContents.articulo import IArticulo
from Products.bpContents.galeria import IGaleria
from Products.bpContents.evento import IEvento
from Products.bpContents.libro import ILibro
from collective.plonefinder.widgets.referencewidget import FinderSelectWidget
from zope.security import checkPermission
from OFS.interfaces import IOrderedContainer

class IArticuloResumenPortlet(IPortletDataProvider):
    documento = schema.Choice(
        title=_(u"Documento"),
        description=_(u"Elija una pagina de la cual mostrará el campo 'Cuerpo'."),
        required=True,
        source=SearchableTextSourceBinder(
                {'object_provides' : (IATDocument.__identifier__,IArticulo.__identifier__,ILibro.__identifier__)},
            default_query='path:'))

class Assignment(base.Assignment):
    implements(IArticuloResumenPortlet)

    def __init__(self, documento=""):
        self.documento= documento

    @property
    def title(self):
        cadena="Resumen articulo"
        return cadena


class Renderer(base.Renderer):
    render = ViewPageTemplateFile('articuloResumen_portlet.pt')

    def __init__(self, *args):
        base.Renderer.__init__(self, *args)

        context = aq_inner(self.context)
        self.portal_transforms = getToolByName(self.context, 'portal_transforms')
        portal_state = getMultiAdapter((context, self.request), name=u'plone_portal_state')
        self.anonymous = portal_state.anonymous()
        self.portal_url = portal_state.portal_url()
        self.typesToShow = portal_state.friendly_types()
        self.portal = getMultiAdapter((self.context, self.request),name=u'plone_portal_state').portal()
        plone_tools = getMultiAdapter((context, self.request), name=u'plone_tools')
        self.catalog = plone_tools.catalog()


    @property
    def available(self):
        """If this portlet has what to show"""
        if checkPermission('zope2.View', self._getContainer(self.data.documento)):
            return self._data() is not None
        else:
            return None

    def getCuerpo(self):
        return self._data()

    def getTitulo(self):
        titulo=self._getContainer(self.data.documento).Title()
        return titulo

    def getResumen(self):
        """Devuelve un diccionario con el resultado"""

        docu=self._getContainer(self.data.documento)
        result=dict()
        result["titulo"]=docu.title
        try:
            result["descri"]=docu.Description()
        except:
            result["descri"]=docu.description

        result["url"]=docu.absolute_url()
        result["imagen"]=self.getIMG("/".join(docu.getPhysicalPath())),


        return result

    def getIMG(self,ruta):
        search=self.catalog(
            path=ruta,
            object_provides="Products.ATContentTypes.interfaces.image.IATImage",
            sort_on='modified',
            sort_order='reverse')

        if len(search)>0:
            imgObj=self.context.unrestrictedTraverse(search[0].getPath())
            return imgObj
        else:
            return None

    def _data(self):
        docu=self._getContainer(self.data.documento)

        try:
            text = docu.description()
        except :
            text = docu.description

        data = self.portal_transforms.convertTo('text/html', text, mimetype='text/-x-web-intelligent')
        html = data.getData()
        return html

    @memoize
    def _getContainer(self, path):
        if not path:
            return None

        if path.startswith('/'):
            path = path[1:]

        if not path:
            return None

        return aq_inner(self.portal).restrictedTraverse(path, default=None)

    def get_position_in_parent(self,obj):
        """ Use IOrderedContainer interface to extract the object's manual ordering position
        """
        parent = obj.aq_inner.aq_parent
        ordered = IOrderedContainer(parent, None)
        if ordered is not None:
            return ordered.getObjectPosition(obj.getId())
        return 0

class AddForm(base.AddForm):

    label = _(u"Agregar portlet")
    description = _(u"Este portlet muestra el contenido del documento que elija.")


    @property
    def form_fields(self):
        form_fields = form.Fields(IArticuloResumenPortlet)
        ## form_fields['documento'].custom_widget =FinderSelectWidget
        return form_fields

    def create(self, data):
        return Assignment(documento=data.get('documento',''))

class EditForm(base.EditForm):
    label = _(u"Editar el portlet")
    description = _(u"Este portlet muestra el contenido del documento que elija.")

    @property
    def form_fields(self):
        form_fields = form.Fields(IArticuloResumenPortlet)
        ##form_fields['documento'].custom_widget = FinderSelectWidget

        return form_fields